#include "./flash/flash.h"

#ifdef USE_FLASH_OPERATION
uint32_t flash_buffer[FLASH_BUFFER_SIZE];
#endif

int flash_read(uint32_t sectoraddr, uint32_t *buf, uint32_t len)
{
	uint32_t *pos = (uint32_t *)sectoraddr;
	
	for(int i = 0; i < len; i++)
	{
		buf[i] = *pos;
		pos++;
	}
	
	pos = (uint32_t *)sectoraddr;
	for(int i = 0; i < len; i++)
	{
		if(buf[i] != *pos)		
		{
			return -1;
		}
		pos++;
	}
	
	return 0;
}

int flash_write(uint32_t sectoraddr, uint32_t *buf, uint32_t len)
{
	uint32_t addr = sectoraddr;
	
	FLASH_Status status = FLASH_COMPLETE;
	FLASH_Unlock();
	FLASH_ClearFlag(FLASH_FLAG_EOP | FLASH_FLAG_PGERR | FLASH_FLAG_WRPRTERR);
	status = FLASH_ErasePage((uint32_t)sectoraddr);
	
	for(int i = 0; i < len; i++)
	{
		while(status != FLASH_COMPLETE)
		{
			
		}
		status = FLASH_ProgramWord(addr, buf[i]);
		addr += 4;
	}
	
	FLASH_Lock();
	
	uint32_t *pos = (uint32_t *)sectoraddr;
	for(int i = 0; i < len; i++)
	{
		if(buf[i] != *pos)		
		{
			return -1;
		}
		pos++;
	}
	
	return 0;
}
